<template>
  <div class="friend-list">
    <h2>好友列表</h2>
    <input type="text" v-model="searchKeyword" placeholder="搜索好友" />
    
    <el-button ref="addFriendButtonRef" @click="handleShowAddFriendPopover">添加好友</el-button>
    <el-popover
      :visible="showAddFriendPopover"
      placement="bottom"
      v-model="showAddFriendPopover"
      :virtual-ref="addFriendButtonRef"
      title="添加好友"
      width="200"
      trigger="click"
    >
      <el-input v-model="newFriendWechatId" placeholder="输入账号添加好友"></el-input>
      <div style="margin-top: 10px; text-align: right;">
        <el-button @click="cancelAddFriend">取消</el-button>
        <el-button type="primary" @click="handleAddFriend">确定</el-button>
      </div>
    </el-popover>
    
    <ul>
      <li
        v-for="friend in filteredFriends"
        :key="friend.friendId"
        class="friend-item"
        :class="{ 'active': selectedFriendId === friend.friendId, 'hover': isHovering === friend.friendId}"
        @mouseenter="handleMouseEnter(friend.friendId)"
        @mouseleave="handleMouseLeave()"
        @click="selectFriend(friend)"
      >
        <img :src="friend.avatar" alt="Avatar" class="avatar" />
        <span class="name">{{ friend.remark || friend.friendId }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed,onMounted} from 'vue';
import { useRouter } from 'vue-router'; // 导入 useRouter
import { useFriendStore } from '../../stores/friendStore';
import {useUserStore} from '@/stores/user'
import { ElPopover, ElInput, ElButton } from 'element-plus';
import request from '@/axios/index'

const friendStore = useFriendStore();
const userStore = useUserStore();
const router = useRouter();
const searchKeyword = ref('');
const selectedFriendId = ref(null);
const isHovering = ref(null);
const showAddFriendPopover = ref(false);
const newFriendWechatId = ref('');
const addFriendButtonRef = ref(null);

// 模拟好友数据
const friends = computed(()=>friendStore.friends) ;

// 计算属性，根据搜索关键字过滤好友列表
const filteredFriends = computed(() => {
  return friends.value.filter(friend => {
    const displayName = friend.remark || friend.name || ''; // 防止 undefined
    return displayName.includes(searchKeyword.value);
  });
});

// 选择好友
const selectFriend = (friend) => {
  friendStore.selectFriend(friend);
  router.push({ path: '/friend', query: {ifAdd:false} });
};

// 其他方法（添加好友等）
const handleMouseEnter = (id) => { isHovering.value = id; };
const handleMouseLeave = () => { isHovering.value = null; };
const handleShowAddFriendPopover = () => { 
  router.push({ path: '/friend', query: {ifAdd:true} });
};
const cancelAddFriend = () => { showAddFriendPopover.value = false; newFriendWechatId.value = ''; };
const handleAddFriend = () => {
  if (newFriendWechatId.value) {
    const newId = Math.max(...friends.value.map(f => f.id)) + 1;
    const newFriend = {
      id: newId,
      name: `新好友${newId}`,
      avatar: 'https://picsum.photos/200/200',
      remark: '',
      friendId: newFriendWechatId.value,
    };
    friends.value.push(newFriend);
    showAddFriendPopover.value = false;
    newFriendWechatId.value = '';
  }
};
const username = ref()

const getFriends = ()=>{
  request.get('/friend/all',{}).then((res)=>{
    console.log("好友列表获取成功",res);
    const cur = [];
    res.forEach(element => {
        if(element.friendId == username.value){
          cur.push({
            id: Date.now().toString(),
            name:element.userId,
            avatar: 'https://picsum.photos/200/200',
            friendId:element.userId,
            remark:element.userId,
          })
        }else{
          cur.push({
            id: Date.now().toString(),
            name:element.friendId,
            avatar: 'https://picsum.photos/200/200',
            friendId:element.friendId,
            remark:element.friendId,
          })
        }
    });
    friendStore.changeFriends(cur);
    // friends.value = cur;    
    console.log("friends：",friends.value);
  })
  .catch((err) => {
      console.error("好友获取失败:", err);
  });
}
onMounted(()=>{
  window.electronAPI.getUsername().then((res)=>{
    username.value = res;
  });
  console.log("username-friendDetail,",username.value);
  getFriends();
})

</script>

<style scoped>
/* 样式略，和原来一样 */
</style>

<style scoped>
.friend-list {
  width: 100%;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.friend-list h2 {
  font-size: 20px;
  margin-bottom: 12px;
  color: #333;
  font-weight: 600;
}

.friend-list input[type="text"] {
  width: 100%;
  padding: 8px 12px;
  margin-bottom: 10px;
  border-radius: 8px;
  border: 1px solid #ccc;
  transition: border-color 0.2s;
}

.friend-list input[type="text"]:focus {
  outline: none;
  border-color: #409EFF;
}

.el-button {
  margin-bottom: 16px;
  width: 100%;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  /* max-height: 400px;
  overflow-y: auto; */
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  border-radius: 10px;
  transition: background-color 0.3s, transform 0.2s;
  margin-bottom: 8px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
}

.friend-item.active,
.friend-item:hover {
  background-color: #e6f7ff;
  transform: scale(1.02);
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 1px solid #ddd;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.el-popover {
  padding: 10px;
}

.el-popover .el-input {
  margin-bottom: 10px;
}

</style>